/**
 * Created By zhangQ 2018/4/25
 * [indexDB 操作]
 */

export function initDb (storeName, name = contant.dbName, version = 1) {
  return new Promise((resolve, reject) => {
    let thisVersion = version || 1
    let request = window.indexedDB.open(name, thisVersion)
    // 数据库打开失败
    request.onerror = (e) => {
      reject(new Error('open Error:' + e.currentTarget.error.message))
    }
    // 数据库版本改变触发
    request.onupgradeneeded = function (e) {
      // var storeNames = db.objectStoreNames
      let db = e.target.result
      for (let key in contant.storeNames) {
        if (db && !db.objectStoreNames.contains(contant.storeNames[key].name)) {
          let store = db.createObjectStore(contant.storeNames[key].name, { keyPath: contant.storeNames[key].index, autoIncrement: false })
          store.createIndex(contant.storeNames[key].index, contant.storeNames[key].index, { unique: true })
        }
      }
      console.log('DB version changed to ' + thisVersion)
    }
    request.onsuccess = function (e) {
      let db = e.target.result
      let stores = []
      for (let key in contant.storeNames) {
        stores.push(contant.storeNames[key].name)
      }
      let transaction = db.transaction(stores, 'readwrite')
      let store = transaction.objectStore(storeName)
      resolve(store)
    }
  })
}

export default initDb
